package com.rabbitmq.ttl;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM20000;

/**
 * 消息过期（通过队列设置）
 */
@Slf4j
public class MsgTTL1a {
    /**
     * 交换器名称
     */
    private static final String EXCHANGE_NAME = "exchange_demo";
    /**
     * 路由键
     */
    private static final String ROUTING_KEY = "routingkey_demo";
    /**
     * 队列名称
     */
    private static final String QUEUE_NAME = "msgTTL1a_demo";

    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();
            // 创建一个 type="direct" 、持久化的、非自动删除的交换器
            channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
            // 创建一个TTL为20秒的队列，消息在队列中会保存20秒
            Map<String, Object> argss = new HashMap<String, Object>();
            argss.put("x-message-ttl", NUM20000);
            channel.queueDeclare(QUEUE_NAME, true, false, false, argss);
            // 将交换器与队列通过路由键绑定
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
            // 发送一条持久化的消息: hello world !
            String message = "Hello World !";
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, message.getBytes());
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
